package com.vnp.vchat.version2;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.vnp.vchat.MainActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.R.anim;
import com.vnp.vchat.R.id;
import com.vnp.vchat.R.layout;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

public class DangNhapActivity extends Activity implements OnClickListener{

	TextView title, btnTaomoi;
	EditText edtTk, edtPass;
	Button btnTieptuc;	
	
	Handler mHandler = new Handler();
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			KeyboardHelper.displaySoftKeyboard(DangNhapActivity.this, edtTk);
		}
	};
	
	PreferenceHelper preferenceHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dang_nhap);
		
		preferenceHelper = new PreferenceHelper(this);
		
		title = (TextView) findViewById(R.id.title);
		btnTaomoi = (TextView) findViewById(R.id.btn_funtion2);
		btnTaomoi.setVisibility(View.VISIBLE);
		
		edtTk = (EditText) findViewById(R.id.edt_phone_email);
		edtPass = (EditText) findViewById(R.id.edt_pass);
		
		btnTieptuc = (Button) findViewById(R.id.btn_tieptuc);
		
		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 300);
		
		setFont();
		
		init();
		nhapTaikhoan();
	}
	
	void nhapTaikhoan(){
		edtTk.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT){
					edtPass.requestFocus();
					return true;
				}
				return false;
			}
		});
		
		edtPass.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_GO){
					checkLogin();
					return true;
				}

				return false;
			}
		});
	}
	
	void login(){
		KeyboardHelper.hideSoftKeyboard(DangNhapActivity.this);
		btnTieptuc.setText("Đang đăng nhập...");
		edtTk.setEnabled(false);
		edtPass.setEnabled(false);
		btnTaomoi.setClickable(false);
		btnTieptuc.setClickable(false);
		
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Log.i("LOGIN", "Error: "+error.toString());
				btnTieptuc.setText("Tiếp tục");
				edtTk.setEnabled(true);
				edtPass.setEnabled(true);
				btnTaomoi.setClickable(true);
				btnTieptuc.setClickable(true);
				Toast.makeText(DangNhapActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
			}
			
			

			@Override
			@Deprecated
			public void onFailure(Throwable error, String content) {
				Log.i("LOGIN", "CONTENT: "+error.toString());
				btnTieptuc.setText("Tiếp tục");
				edtTk.setEnabled(true);
				edtPass.setEnabled(true);
				btnTaomoi.setClickable(true);
				btnTieptuc.setClickable(true);
				Toast.makeText(DangNhapActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
			}



			@Override
			public void onSuccess(JSONObject re) {
				
				Log.i("LOGIN", ""+re.toString());
				try {
					int status = re.getInt("status");
					if (status == 1){
		            	
		            	JSONObject uinf = re.getJSONObject("uinfo");
		            	JSONObject settings = re.getJSONObject("setting");
		            	
		            	preferenceHelper.setUserId(uinf.getString("use_sso_id"));
		            	preferenceHelper.setHash(re.getString("hash"));
		            	preferenceHelper.setHashSetting(re.getString("hash_setting"));
		            	preferenceHelper.setDomainConnect(re.getString("domain_connect"));
		            	preferenceHelper.setPostConnect(re.getString("port_connect"));
		            	preferenceHelper.setDataJoin(re.getString("datajoin"));
		            	preferenceHelper.setSettingNotifi(settings.getString("notifi"));
		            	preferenceHelper.setSettingFeed(settings.getString("feed"));
		            	preferenceHelper.setSettingDisplay(settings.getString("showmsg"));
		            	preferenceHelper.setUserName(uinf.getString("name"));
		            	preferenceHelper.setMyAvatar(uinf.getString("imaege"));
		            	preferenceHelper.setEmail(uinf.getString("email"));
//		            	preferenceHelper.setPhone(value)
		            	gotoMain();
		            	
		            } else if (status == 0) {
		            	btnTieptuc.setText("Tiếp tục");
		            	edtTk.setEnabled(true);
						edtPass.setEnabled(true);
						btnTaomoi.setClickable(true);
						btnTieptuc.setClickable(true);
						Toast.makeText(DangNhapActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
		            }
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		String hash = Utils.MD5(""+Common.KEY_HTTP+"|"+""+edtTk.getText().toString()+"|"+""+edtPass.getText().toString());
		
		Log.i("LOGIN", "HASH: "+hash);
		
		httpClientHelper.loginByPhoneOrEmail(edtTk.getText().toString(), edtPass.getText().toString(), hash, Common.KEY_HTTP);
	}
	
	void setFont(){
		title.setTypeface(Utils.getTypefaceBold(DangNhapActivity.this));
		btnTaomoi.setTypeface(Utils.getTypefaceRegular(DangNhapActivity.this));
		
		edtTk.setTypeface(Utils.getTypefaceRegular(DangNhapActivity.this));
		edtPass.setTypeface(Utils.getTypefaceRegular(DangNhapActivity.this));
		btnTieptuc.setTypeface(Utils.getTypefaceMedium(DangNhapActivity.this));
	}
	
	void gotoMain(){
		Intent t = new Intent(DangNhapActivity.this, MainActivity.class);
		finish();
		/** on your logout method:**/
		/*Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("com.package.FINISH");
		sendBroadcast(broadcastIntent);*/
		startActivity(t);
	}
	
	void init(){
		title.setText("Đăng nhập");
		btnTaomoi.setOnClickListener(this);
		btnTieptuc.setOnClickListener(this);
		btnTieptuc.setText("Tiếp tục");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_tieptuc:
			checkLogin();
			break;
		case R.id.btn_funtion2:
			gotoDangki();
			break;

		default:
			break;
		}
	}
	
	void checkLogin(){
		if (edtTk.getText().toString().equals("")){
			Toast.makeText(DangNhapActivity.this, "Tài khoản không được để trống!", Toast.LENGTH_SHORT).show();
		} else {
			if (edtPass.getText().toString().equals("")) {
				Toast.makeText(DangNhapActivity.this, "Pass không được để trống!", Toast.LENGTH_SHORT).show();	
			} else {
				login();
//				Toast.makeText(DangNhapActivity.this, "Bat dau login!", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	
	
	@Override
	protected void onPause() {
		super.onPause();
		KeyboardHelper.hideSoftKeyboard(DangNhapActivity.this);
	}
	
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacksAndMessages(null);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	void gotoDangki(){
		Intent t = new Intent(DangNhapActivity.this, DangkiNhapPhoneActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}
	
	void showDialogDangNhapThatBai(){
		
	}

}
